package br.com.ordersys.web.menu;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import br.com.ordersys.framework.db.DBSessionManager;
import br.com.ordersys.framework.db.IDBSession;
import br.com.ordersys.framework.db.IValueObject;
import br.com.ordersys.framework.db.Query;
import br.com.ordersys.framework.db.Query.RowIterator;

public class MenuHelper {
	public Menu build() {
		IDBSession dbSession = null;
		try {
			dbSession = DBSessionManager.open();
			final List<MenuItem> roots = new ArrayList<MenuItem>();
			final Map<String, MenuItem> itens = new HashMap<String, MenuItem>();

			Query<IValueObject> qmenu = dbSession.buildQuery("T00ITEMMENU");
			qmenu.setCriteria("this.PROFILEID = 0"); // se for preciso termos mais de um menu então devemos obter esse valor de algum parametro

			qmenu.iterate(new RowIterator<IValueObject>() {

				@Override
				public void next(IValueObject vo) {
					MenuItem mi = new MenuItem();

					mi.setId(vo.asString("ID"));
					mi.setDescription(vo.asString("DESCRICAO"));
					mi.setContentUrl(vo.asString("CONTENTURL"));
					mi.setImageUrl(vo.asString("IMAGEURL"));

					if (vo.asObject("PARENTID") == null) {
						roots.add(mi);
					} else {
						mi.setParentId(vo.asString("PARENTID"));
					}

					itens.put(mi.getId(), mi);
				}
			});

			for (Iterator<Entry<String, MenuItem>> ite = itens.entrySet().iterator(); ite.hasNext();) {
				MenuItem mi = ite.next().getValue();

				if (mi.getParentId() != null) {
					MenuItem pmi = itens.get(mi.getParentId());
					List<MenuItem> children = pmi.getSubMenu();

					if (children == null) {
						children = new ArrayList<MenuItem>();
						pmi.setSubMenu(children);
					}

					children.add(mi);
				}
			}

			Menu m = new Menu(roots);
			
			m.sort();
			
			return m;
		} finally {
			DBSessionManager.close(dbSession);
		}
	}
}
